package com.parking.common.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.parking.common.dao.IBaseDao;

/**
 * 基础DAO实现类
 * @param <E> 实体类型
 * @param <PK> 实体主键类型
 */
public class BaseDaoImpl<E extends java.io.Serializable, PK extends java.io.Serializable> implements IBaseDao<E, PK>{

	@Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
	 
	public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
	
	@Override
	public Object save(E entity) {
		return getSession().save(entity);
	}

	@Override
	public void update(E entity) {
		getSession().update(entity);
	}

	@Override
	public long countAll(String hql, Map<String, Object> params) {
		Query query = getSession().createQuery(hql);
		setParams(query, params);
		return (Long)query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> find(String hql, Map<String, Object> params) {
		Query query = getSession().createQuery(hql);
		setParams(query, params);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public E unique(String hql, Map<String, Object> params) {
		Query query = getSession().createQuery(hql);
		setParams(query, params);
		return (E) query.setMaxResults(1).uniqueResult();
	}

    protected void setParams(Query query, Map<String, Object>params) {
    	Set<String> keys = params.keySet();
    	Iterator<String> it = keys.iterator();
    	while (it.hasNext()) {
    		String key = it.next();
    		query.setParameter(key, params.get(key));
    	}
    }

    @SuppressWarnings("unchecked")
	@Override
	public List<E> find(String hql, Map<String, Object> params, int pageSize,
			int pageNum) {
		Query query = getSession().createQuery(hql);
		setParams(query, params);
		if (pageNum >= 0 && pageSize > 0) {
            query.setMaxResults(pageSize);
            int start = pageNum * pageSize;
            if (start != 0) {
                query.setFirstResult(start);
            }
        }
		return query.list();
	}
}
